package com.falcon.scanner.impl;

import cn.hutool.core.io.FileUtil;
import com.falcon.core.enums.ResponseCodeEnum;
import com.falcon.core.utils.AssertUtil;
import com.falcon.scanner.IVueComponentScanner;
import com.falcon.domain.po.MenuComponentPO;
import com.swan.core.utils.TxtFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zongf
 * @date 2024-03-14
 **/
@Slf4j
@Service
public class VueComponentScanner implements IVueComponentScanner {

    public List<MenuComponentPO> doScan(String baseDirPath) {
        log.info("扫描目录:{}",baseDirPath);

        File basDir = new File(baseDirPath);
        AssertUtil.assertTrue(basDir.exists(), ResponseCodeEnum.GEN, "目录不存在");
        AssertUtil.assertTrue(basDir.isDirectory(),ResponseCodeEnum.GEN, "不是目录");

        // 扫描组件文件
        List<File> componentFiles = new ArrayList<>();
        findComponentFile(componentFiles, basDir);

        List<MenuComponentPO> menuComponentPOList = componentFiles.stream()
                .map(file -> this.parseFile(file, baseDirPath))
                .collect(Collectors.toList());

        return menuComponentPOList;
    }

    private MenuComponentPO parseFile(File file, String baseDirPath) {

        String absFilePath = file.getAbsolutePath();
        String relativeFilePath = StringUtils.substringAfter(absFilePath, baseDirPath);
        String moduleName = StringUtils.substringBetween(relativeFilePath, "/", "/");

        MenuComponentPO menuComponentPO = new MenuComponentPO();
        menuComponentPO.setModuleName(moduleName);
        menuComponentPO.setSrcPath(formatPathSeparator(relativeFilePath));
        menuComponentPO.setStatus(1);
        menuComponentPO.setCreateTime(FileUtil.lastModifiedTime(file));

        for (String line : TxtFileUtil.readFile(file.getAbsolutePath())) {
            if (line.contains("defineOptions")) {
                String name = StringUtils.substringBetween(line, "name: '", "'");
                menuComponentPO.setName(name);
            }
        }

        return menuComponentPO;
    }


    private void findComponentFile(List<File> resultList, File file) {
        if (file.isDirectory()) {
            for (File subDirectory : file.listFiles()) {
                findComponentFile(resultList, subDirectory);
            }
            return;
        }

        if (file.getName().equals("index.vue")) {
            resultList.add(file);
        }
    }

    private String formatPathSeparator(String path) {
        return path.replaceAll("\\\\", "/");
    }

}


